package com.hxy.user.interceptor;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        if (token != null) {
            Object obj = redisTemplate.opsForValue().get(token);
            if (obj != null) { // 登录了没过期
                redisTemplate.opsForValue().set(token,obj,30, TimeUnit.MINUTES);
                // 放行
                return true;
            }
        }
        // 跳转登录页面
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");

        response.getWriter().write("{\"success\":false,\"msg\":\"noLogin\"}");
        return false;
    }
}






















